import {
    LocationQueryRaw,
    LocationQueryValueRaw, RouteLocationPathRaw,
    RouteLocationRaw,
    RouteRecordRaw,
    RouterView,
    useRoute
} from "vue-router";
import {isExternal} from "@/utils/validate";
import {EMenuType} from "@/config/enums";
import Layout from "@/layout/index.vue";
import router, {INDEX_ROUTE_NAME} from "@/base/router";
import useUserStore from "@/base/stores/modules/user";


const modules = import.meta.glob('/src/views/**/*.vue')


class RouterManager {

    /**
     * 过滤路由所需要的数据
     * @param routes
     * @param firstRoute
     */
    filterAsyncRoutes(routes: any[], firstRoute = true): RouteRecordRaw[] {
        return routes.map((route) => {
            // 创建路由记录
            const routeRecord: RouteRecordRaw = this.createRouteRecord(route, firstRoute)

            if (route.children != null && route.children && route.children.length) {
                routeRecord.children = this.filterAsyncRoutes(route.children, false)
            }
            return routeRecord
        })

    }


    /**
     *
     * 组装路由类
     *
     * @param route
     * @param firstRoute
     */
    createRouteRecord(route: any, firstRoute: boolean): RouteRecordRaw {

        // @ts-ignore
        const routeRecord: RouteRecordRaw = {
            path: isExternal(route.paths) ? route.paths : firstRoute ? `/${route.paths}` : route.paths,
            name: Symbol(route.name),
            meta: {
                hidden: !route.isShow,
                keepAlive: !!route.isCache,
                title: route.menuName,
                perms: route.perms,
                query: route.params,
                icon: route.menuIcon,
                type: route.menuType,
                activeMenu: route.selected
            }
        }


        // 配置组件
        switch (route.menuType) {
            // 枚举页面  RouterView 用户当前路由
            case EMenuType.CATALOGUE:
                // 判断是否是第一个路由
                routeRecord.component = firstRoute ? shallowRef(Layout) : shallowRef(RouterView)

                // 没有子类 用当前路由
                if (!route.children) {
                    routeRecord.component = shallowRef(RouterView)
                }

                break

            // 主页面
            case EMenuType.MENU:
                routeRecord.component = this.loadRouteView(route.component)
                break
        }


        return routeRecord
    }


    /**
     * 动态加载组件
     */
    loadRouteView(component: string) {
        try {
            const key = Object.keys(modules).find((key) => {
                return key.includes(`${component}.vue`)
            })

            if (key) {
                return modules[key]
            }

        } catch (error) {
            console.error(error)
            return shallowRef(RouterView)
        }
    }





    /**
     * 找到第一个有效的路由
     * @param routes
     */
    findFirstValidRoute(routes: RouteRecordRaw[]): string | undefined {
        for (const route of routes) {
            if (route.meta?.type == EMenuType.MENU && !route.meta?.hidden && !isExternal(route.path)) {
                return route.name as string
            }

            if (route.children) {
                const name = this.findFirstValidRoute(route.children)
                if (name) {
                    return name
                }
            }
        }

    }

    /**
     * 重置路由
     */
    resetRouter() {
        router.removeRoute(INDEX_ROUTE_NAME)
        const {routes} = useUserStore()

        routes.forEach((route: any) => {
            const name = route.name
            if (name && router.hasRoute(name)) {
                router.isReady().then(() => {
                    router.removeRoute(name)
                });
            }
        })

    }


    /**
     * 通过权限字符查询路由路径
     * @param perms
     */
    getRoutePath(perms: string) {
        const routerObj = useRouter() || router
        return routerObj.getRoutes().find((item) => item.meta?.perms == perms)?.path || ''
    }


    /**
     *  根据组件名称获取路由路径
     * @author 徐寿春
     * 2023/4/6 10:09
     */
    getRoutePathByName(perms: string): string | undefined {
        let userStore = useUserStore();
        return this.findComponent(userStore.menu, perms);
    }




    /**
     *  根据组件名称获取路由路径
     * @author 徐寿春
     * 2023/4/6 10:09
     */
    pushByPath(path: string, perms?: LocationQueryRaw) {
        let routePathByName = this.getRoutePathByName(path);
        if (!!routePathByName) {

            const requests: RouteLocationRaw = {
                path: routePathByName,
                query: perms
            }

            router.push(requests).catch(err => {
                console.log("路由错误信息", err)
            })
        }
    }


    findComponent(arr: any [], perms: string): string | undefined {
        const map: string [] = arr.map((item) => {
                if (item.component === perms) {
                    return item.name
                } else if (!!item.children && item.children.length > 0) {
                    return this.findComponent(item.children, perms)
                }
            }
        );
        return map.find(items => !!items)
    }

    /**
     * 路由跳转
     *
     * @author 徐寿春
     * 2023/4/4 15:21
     */
    pushRoutePath(keyWord: string) {
        router.push(keyWord).then((rsp) => {
        }, () => {
        })
    }

    /**
     * 路由跳转
     *
     * @author 徐寿春
     * 2023/4/4 15:21
     */
    pushRoutePathReplace(keyWord: string) {
        router.replace(keyWord).then(() => {
        })
    }

}

const routerManager = new RouterManager();
export default routerManager

